import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { useNavigate } from 'react-router-dom';
import './Login.css';

interface User {
  username: string;
  password: string;
  image: string;
}

interface LoginProps {
  onLoginSuccess?: (userData: {
    username: string;
    isLoggedIn: boolean;
    image: string;
  }) => void;
}

const Login: React.FC<LoginProps> = ({ onLoginSuccess }) => {
  const navigate = useNavigate();
  const [isLogin, setIsLogin] = useState(true);
  const [formData, setFormData] = useState({
    username: '',
    password: '',
    image: '',
  });
  const [message, setMessage] = useState('');
  const [localUsers, setLocalUsers] = useState<User[]>([]);
  const [showAvatarSelector, setShowAvatarSelector] = useState(false);

  // 头像图片列表
  const avatarImages = [
    '/img/1.png',
    '/img/2.png',
    '/img/3.png',
    '/img/4.png',
    '/img/5.png',
    '/img/6.png',
    '/img/7.png',
  ];

  // 从本地存储加载用户数据
  useEffect(() => {
    const savedUsers = localStorage.getItem('users');
    if (savedUsers) {
      setLocalUsers(JSON.parse(savedUsers));
    }
  }, []);

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: value,
    }));
  };

  const handleAvatarSelect = (avatarPath: string) => {
    setFormData(prev => ({
      ...prev,
      image: avatarPath,
    }));
    setShowAvatarSelector(false);
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setMessage('');

    if (isLogin) {
      // 登录逻辑
      try {
        const response = await axios.post('http://localhost:3001/ysx/login', {
          username: formData.username,
          password: formData.password,
          image: formData.image,
        });

        if (response.data.code === 200) {
          setMessage('登录成功！');
          // 保存登录状态到本地存储
          const userData = {
            _id: response.data.data._id,
            username: formData.username,
            isLoggedIn: true,
            image: formData.image,
          };
          localStorage.setItem('currentUser', JSON.stringify(userData));
          // 调用父组件的登录成功回调（如果存在）
          if (onLoginSuccess) {
            onLoginSuccess(userData);
          }
          // 跳转到Chat页面
          setTimeout(() => {
            navigate('/');
          }, 1000); // 延迟1秒跳转，让用户看到成功消息
        } else {
          setMessage(response.data.msg);
        }
      } catch (error: unknown) {
        console.error('登录错误:', error);
        // 优先显示后端返回的错误信息
        if (error && typeof error === 'object' && 'response' in error) {
          const axiosError = error as {
            response?: { data?: { msg?: string }; status?: number };
          };
          if (axiosError.response?.data?.msg) {
            setMessage(axiosError.response.data.msg);
          } else if (axiosError.response?.status) {
            // 根据HTTP状态码显示相应错误
            switch (axiosError.response.status) {
              case 400:
                setMessage('请求参数错误');
                break;
              case 401:
                setMessage('用户名不存在');
                break;
              case 402:
                setMessage('用户名和密码不能为空');
                break;
              case 500:
                setMessage('服务器错误');
                break;
              default:
                setMessage('登录失败，请稍后重试');
            }
          }
        } else if (error && typeof error === 'object' && 'request' in error) {
          setMessage('登录失败，请检查网络连接或确保后端服务器已启动');
        } else {
          setMessage('登录失败，请稍后重试');
        }
      }
    } else {
      // 注册逻辑
      if (!formData.image) {
        setMessage('请选择头像');
        return;
      }

      try {
        const response = await axios.post(
          'http://localhost:3001/ysx/register',
          {
            username: formData.username,
            password: formData.password,
            image: formData.image,
          }
        );

        if (response.data.code === 200) {
          setMessage('注册成功！');
          setIsLogin(true);
          // 保存新用户到本地存储
          const newUser: User = {
            username: formData.username,
            password: formData.password,
            image: formData.image,
          };
          const updatedUsers = [...localUsers, newUser];
          setLocalUsers(updatedUsers);
          localStorage.setItem('users', JSON.stringify(updatedUsers));

          // 清空表单
          setFormData({ username: '', password: '', image: '' });
        } else {
          setMessage(response.data.msg);
        }
      } catch (error: unknown) {
        console.error('注册错误:', error);
        // 优先显示后端返回的错误信息
        if (error && typeof error === 'object' && 'response' in error) {
          const axiosError = error as {
            response?: { data?: { msg?: string }; status?: number };
          };
          if (axiosError.response?.data?.msg) {
            setMessage(axiosError.response.data.msg);
          } else if (axiosError.response?.status) {
            // 根据HTTP状态码显示相应错误
            switch (axiosError.response.status) {
              case 400:
                setMessage('用户名已存在');
                break;
              case 500:
                setMessage('服务器错误');
                break;
              default:
                setMessage('注册失败，请稍后重试');
            }
          }
        } else if (error && typeof error === 'object' && 'request' in error) {
          setMessage('注册失败，请检查网络连接或确保后端服务器已启动');
        } else {
          setMessage('注册失败，请稍后重试');
        }
      }
    }
  };

  const toggleMode = () => {
    setIsLogin(!isLogin);
    setMessage('');
    setFormData({ username: '', password: '', image: '' });
    setShowAvatarSelector(false);
  };

  return (
    <div className="login-container">
      <div className="login-box">
        <h2>{isLogin ? '登录' : '注册'}</h2>

        <form onSubmit={handleSubmit} className="login-form">
          <div className="form-group">
            <label>用户名：</label>
            <input
              type="text"
              name="username"
              value={formData.username}
              onChange={handleInputChange}
              required
              placeholder="请输入用户名"
            />
          </div>

          <div className="form-group">
            <label>密码：</label>
            <input
              type="password"
              name="password"
              value={formData.password}
              onChange={handleInputChange}
              required
              placeholder="请输入密码"
            />
          </div>

          {!isLogin && (
            <div className="form-group">
              <label>选择头像：</label>
              <div className="avatar-selector">
                {formData.image ? (
                  <div className="selected-avatar">
                    <img src={formData.image} alt="已选头像" />
                    <button
                      type="button"
                      onClick={() => setShowAvatarSelector(!showAvatarSelector)}
                      className="change-avatar-btn"
                    >
                      更换头像
                    </button>
                  </div>
                ) : (
                  <button
                    type="button"
                    onClick={() => setShowAvatarSelector(!showAvatarSelector)}
                    className="select-avatar-btn"
                  >
                    点击选择头像
                  </button>
                )}

                {showAvatarSelector && (
                  <div className="avatar-grid">
                    {avatarImages.map((avatar, index) => (
                      <div
                        key={index}
                        className="avatar-option"
                        onClick={() => handleAvatarSelect(avatar)}
                      >
                        <img src={avatar} alt={`头像${index + 1}`} />
                      </div>
                    ))}
                  </div>
                )}
              </div>
            </div>
          )}

          <button type="submit" className="submit-btn">
            {isLogin ? '登录' : '注册'}
          </button>
        </form>

        {message && (
          <div
            className={`message ${message.includes('成功') ? 'success' : 'error'}`}
          >
            {message}
          </div>
        )}

        <div className="toggle-mode">
          <button type="button" onClick={toggleMode} className="toggle-btn">
            {isLogin ? '没有账号？点击注册' : '已有账号？点击登录'}
          </button>
        </div>
      </div>
    </div>
  );
};

export default Login;
